package game.graphics;

import static org.lwjgl.opengl.GL11.glColor3f;

import java.io.Serializable;

import application.Configuration;

/**
 * Generate light.
 * 
 * @author Tomas Zima
 */
public class Light implements Serializable
{
	/**
	 * Constructor.
	 * 
	 * @param blocks
	 * @param screenWidth
	 * @param screenHeight
	 */
	public Light(Block[][] blocks, int screenWidth, int screenHeight)
	{
		this.blocks			= blocks;
		this.screenWidth	= screenWidth;
		this.screenHeight	= screenHeight;
	}

	/**
	 * Draw light
	 * 
	 * @param cameraX
	 * @param cameraY
	 * @param lightX
	 * @param lightY
	 * @param radius
	 * @param intensity
	 * @param deltaIntensity
	 */
	public void redraw(int cameraX, int cameraY, int lightX, int lightY, int radius, float intensity, float deltaIntensity)
	{
		// Block where the camera looks
		int blockCameraX		= cameraX / Configuration.BLOCK_SIZE;
		int blockCameraY		= cameraY / Configuration.BLOCK_SIZE;
		
		// Block where the light will be centered
		int blockLightX			= lightX;
		int blockLightY			= lightY;
		
		// Light intensity in the specified place
		float col				= intensity - deltaIntensity * 2.0f * (float) radius;
		
		// Drawing loop
		for (int i = -radius; i < radius; i++)
		{
			// Set color (intensity of light)
			glColor3f(col, col, col);
			
			// Recalculate intensity for lines
			if (i < 0)
			{
				col	+= deltaIntensity;
			}
			else
			{
				col -= deltaIntensity;
			}
			
			// Drawing loop
			for (int j = -radius; j < radius; j++)
			{
				// Recalculate intensity for columns
				if (j < 0)
				{
					col += deltaIntensity;
				}
				else
				{
					col -= deltaIntensity;
				}
				
				// Set light
				glColor3f(col, col, col);

				// Redraw block
				blocks[blockLightX + i][blockLightY + j].redraw((blockLightX - blockCameraX) * Configuration.BLOCK_SIZE + screenWidth / 2 + i * Configuration.BLOCK_SIZE, (blockLightY - blockCameraY) * Configuration.BLOCK_SIZE + screenHeight / 2 + j * Configuration.BLOCK_SIZE);
			}
		}
	}
	
	private Block[][]	blocks;
	private int			screenWidth;
	private int			screenHeight;;
}
